<!--
 * @Descripttion: 
 * @Author: jhw
 * @Date: 2024-06-25 14:32:41
 * @LastEditors: jhw
 * @LastEditTime: 2024-06-27 16:01:52
-->
<template>
  <div class="dialogform">
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改' : '新增'"
      width="600"
      :destroy-on-close="true"
      :before-close="handleClosed"
    >
      <JForm ref="JFormRef" v-model="formValue" :list="configList" :rules="formRules" :dict="dict"></JForm>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClosed">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import JForm from '@/components/JForm/index.vue';
import { IListPropsType } from '@/components/JForm/config';
import type { FormRules } from 'element-plus';

const JFormRef = ref();

interface IQueryForm {
  name: string;
  age: number;
  sex: string;
  datepicker: string;
  select2: string;
  timepicker: string;
  treeSelect: string;
  cascader: string;
  radio: string;
  rate: number;
  slider: number;
  switch: number;
  checkbox: Array<string | number>;
  colorpicker: string;
}

const dict = reactive<any>({});
const configList = ref<IListPropsType<IQueryForm>>([
  {
    label: 'input',
    prop: 'name',
    fieldType: 'input',
  },
  {
    label: 'input',
    prop: 'age',
    fieldType: 'input',
  },
  {
    label: 'select',
    prop: 'sex',
    fieldType: 'select',
    options: [
      {
        label: '男',
        value: '1',
      },
      {
        label: '女',
        value: '2',
      },
    ],
  },
  {
    label: 'datepicker',
    prop: 'datepicker',
    fieldType: 'datepicker',
    otherProps: {
      valueFormat: 'YYYY-MM-DD',
    },
  },
  // {
  //   label: '测试select2',
  //   prop: 'select2',
  //   fieldType: 'select2',
  //   options: [
  //     {
  //       label: '选项1',
  //       value: '1',
  //     },
  //     {
  //       label: '选项2',
  //       value: '2',
  //     },
  //   ],
  //   otherProps: {},
  // },
  {
    label: 'timepicker',
    prop: 'timepicker',
    fieldType: 'timepicker',
    otherProps: {
      valueFormat: 'HH:mm:ss',
    },
  },
  {
    label: 'cascader',
    prop: 'cascader',
    fieldType: 'cascader',
    options: [
      {
        value: 'guide',
        label: 'Guide',
        children: [
          {
            value: 'disciplines',
            label: 'Disciplines',
            children: [
              {
                value: 'consistency',
                label: 'Consistency',
              },
              {
                value: 'feedback',
                label: 'Feedback',
              },
              {
                value: 'efficiency',
                label: 'Efficiency',
              },
              {
                value: 'controllability',
                label: 'Controllability',
              },
            ],
          },
        ],
      },
    ],
    otherProps: {},
    callback: (val: any) => {
      console.log('val', val);
    },
  },
  {
    label: 'radio',
    prop: 'radio',
    fieldType: 'radio',
    options: [
      {
        label: '选项1',
        value: '1',
      },
      {
        label: '选项2',
        value: '2',
      },
    ],
  },
  {
    label: 'rate',
    prop: 'rate',
    fieldType: 'rate',
    otherProps: {
      max: 5,
      // 半角
      allowHalf: true,
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
    },
  },
  // {
  //   label: 'slider',
  //   prop: 'slider',
  //   fieldType: 'slider',
  //   otherProps: {
  //     max: 100,
  //     min: 0,
  //     step: 0.1, // 步长
  //   },
  // },
  {
    label: 'switch',
    prop: 'switch',
    fieldType: 'switch',
    otherProps: {
      activeValue: 1,
      inactiveValue: 0,
    },
  },
  {
    label: 'treeSelect',
    prop: 'treeSelect',
    fieldType: 'treeselect',
    options: [
      {
        label: '选项1',
        value: '1',
        children: [
          {
            label: '选项1-1',
            value: '1-1',
          },
          {
            label: '选项1-2',
            value: '1-2',
          },
        ],
      },
      {
        label: '选项2',
        value: '2',
        children: [
          {
            label: '选项2-1',
            value: '2-1',
          },
          {
            label: '选项2-2',
            value: '2-2',
          },
        ],
      },
    ],
    otherProps: {
      multiple: true, // 多选
      'show-checkbox': true, // 复选框
      'check-strictly': true, // 父子节点不联动
      'check-on-click-node': true, // 点击节点即选中
      filterable: true, // 可搜索
      'filter-method': (query: string, item: any) => {
        console.log('query参数', query);
        console.log('item', item);
      },
    },
  },
  {
    label: 'checkbox',
    prop: 'checkbox',
    fieldType: 'checkbox',
    options: [
      {
        label: '选项1',
        value: '1',
      },
      {
        label: '选项2',
        value: '2',
      },
    ],
    isShowCheckAll: true, // 是否显示全选按钮
    callback: (val: string[] | number[] | boolean) => {
      console.log('选中的值', val);
    },
    otherProps: {
      min: 1, // 最少选中
      max: 2, // 最多选中
    },
  },
  // {
  //   label: 'colorpicker',
  //   prop: 'colorpicker',
  //   fieldType: 'color',
  //   otherProps: {},
  // },
]);

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入年龄'));
  } else {
    if (value < 18) {
      callback(new Error('必须年满18岁'));
    } else {
      callback();
    }
  }
};

const formRules = reactive<FormRules<typeof formValue>>({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    {
      validator: validatePass2,
    },
  ],
});

const formValue = ref<Partial<IQueryForm>>({
  name: '',
  age: undefined,
  datepicker: '',
  sex: '',
  select2: '',
  timepicker: '',
  treeSelect: '',
  radio: '',
  rate: 0,
  slider: 0,
  switch: 0,
  checkbox: [],
  colorpicker: '',
});

const isEdit = ref(false);
const dialogVisible = ref(false);

// 关闭
const handleClosed = () => {
  JFormRef.value.onReset();
  for (const key in formValue.value) {
    if (formValue.value.hasOwnProperty(key)) {
      formValue.value[key as keyof IQueryForm] = undefined;
    }
  }
  // 单独处理checkbox
  configList.value.forEach((item) => {
    if (item.fieldType === 'checkbox') {
      item.checkAll = false;
    }
  });
  dialogVisible.value = false;
};

const handleOpen = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  isEdit.value = true;
  formValue.value = { ...row };
  // 单独处理checkbox
  if (formValue.value.checkbox?.length) {
    configList.value.forEach((item) => {
      if (item.fieldType === 'checkbox') {
        item.checkAll = true;
        item.isIndeterminate = (formValue.value.checkbox?.length &&
          formValue.value.checkbox?.length > 0 &&
          formValue.value.checkbox?.length < ((item.extra ? dict[item.extra] : item.options) || []).length) as boolean;
      }
    });
  }
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  const res = await JFormRef.value.validateForm();
  if (!res) return;
  console.log(JSON.parse(JSON.stringify(formValue.value)));
};

defineExpose({
  handleOpen,
  handleEdit,
});
</script>

<style scoped></style>
